home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14311 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: news.logicon.com!newsmaster@klee
  2. From: kkolda@logicon.com (Kenneth D. Kolda)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Derivation and calling virtual functions
  5. Date: 29 Mar 1996 18:42:23 GMT
  6. Organization: Logicon Operating Systems
  7. Message-ID: <4jhauf$pf4@piper.logicon.com>
  8. References: <graphix.828032689@spiff.cc.iastate.edu>
  9. NNTP-Posting-Host: 137.51.122.161
  10. Mime-Version: 1.0
  11.  
  12. In article <graphix.828032689@spiff.cc.iastate.edu>, graphix@iastate.edu 
  13. says...
  14. >
  15. >  Say we have the following:
  16. >
  17. >class Base {
  18. >public:
  19. >  virtual void func() { // some stuff }
  20. >  virtual void write() { func(); };
  21. >};
  22. >
  23. >class Derived : public Base {
  24. >public:
  25. >  void func() { // some stuff }
  26. >  write(); { Base::func(); }
  27. >};
  28. >
  29. >Derived inst;
  30. >
  31. >  Now, when I call inst.write() it in turn calls Bass::write() which in
  32. >turn calls Base::func().  Is there a way to instead have it call
  33. >Derived::func() if the instance is of type Derived?  I hoped the 
  34. >virtual keyword would help in this case.
  35. >
  36. >  Thanks.
  37. >
  38. >-- 
  39. >Kent Vander Velden
  40. >graphix@iastate.edu
  41. >
  42.  
  43.  
  44. First, I'm going to assume that you have some typos -- namely that
  45. Derived::write() should be as follows:
  46.  
  47.     void Derived::write() 
  48.     { Base::write(); // instead of Base::func() }
  49.  
  50. Now, when you call inst.write(), it will call Base::write() (as you 
  51. described) BUT it *should* then call Derived::func().  If your compiler 
  52. causes Base::func() to be called, there's a problem since the virtual 
  53. keyword should definitely trip the call into the derived class.
  54.  
  55.     The other possibility is that the prototypes of your func() 
  56. methods are not exactly the same (all parameter types and return value 
  57. type).  In this case the virtual mechanism gets overridden and what you 
  58. described would occur.  
  59.  
  60. Ken Kolda
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.